package com.knife.blog.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.knife.web.Globals;

public class BlogTagetUtil {
	public static String getImgTag(String src,int width,int height){
		double ratio = 0.0;
		int imgWidth = 0;
		int imgHeight = 0;
		File file = new File(Globals.APP_BASE_DIR,src);
		try {
			BufferedImage bi = ImageIO.read(file);

			if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
				if (bi.getHeight() > bi.getWidth()){
					ratio = (double)height / bi.getHeight();
					imgWidth = new Double(bi.getWidth()*ratio).intValue();
					imgHeight = height;
				}
				else{
					ratio = (double)width / bi.getWidth();
					imgHeight = new Double(bi.getHeight()*ratio).intValue();
					imgWidth = width;
				}
			}else{
				imgWidth = width;
				imgHeight = height;
			}
			
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return createImgTag(src,imgWidth,imgHeight);
	}
	
	public static String createImgTag(String src,int width,int height){
		StringBuffer imgTag = new StringBuffer();
		imgTag.append("<img src='");
		imgTag.append(src);
		imgTag.append("' width='");
		imgTag.append(width);
		imgTag.append("' height='");
		imgTag.append(height);
		imgTag.append("'/>");
		return imgTag.toString();
	}

}
